/**
 * Default dev server configuration.
 */
const webpack = require('webpack');
const WebpackBaseConfig = require('./Base');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

const PORT = process.env.PORT && Number(process.env.PORT);
const HappyPack = require('happypack');
const os = require('os');

const happyThreadPool = HappyPack.ThreadPool({size: os.cpus().length});
const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const FriendlyErrors = require('friendly-errors-webpack-plugin');

class WebpackDevConfig extends WebpackBaseConfig {

  constructor() {
    super();
    this.config = {
      mode: 'development',
      devtool: 'cheap-module-eval-source-map',
      entry: {
        app: [
          'react-hot-loader/patch',
          'webpack-dev-server/client?http://localhost:8001/',
          'webpack/hot/only-dev-server',
          './client.js'
        ],
      },
      devServer: {
        contentBase: './src/',
        publicPath: '/assets/',
        historyApiFallback: true,
        hot: true,
        inline: true,
        quiet: true,  // 隐藏打包日志
        port: PORT || 8002,
        disableHostCheck: true,
        proxy: [{
          context: ['/maps'],
          target: 'https://maps.googleapis.com',
          secure: false,
          changeOrigin: true
        },
          {
            context: [
              '/push', '/budget-service', '/brms', '/operationservice',
              '/vendor-data-service', '/vendor-info-service', '/location-service',
              '/report', '/mobile', '/notification', '/supplier', '/alipay', '/contract', '/open'
              , '/invoice', '/config', '/receipt', 'public'
            ],
            target: 'https://mcdtest2019.huilianyi.com',
            secure: false,
            changeOrigin: true
          },
          {
            context: [
              '/api'
            ],
            target: 'https://mcdtest2019.huilianyi.com',
            // target: 'http://localhost:9083',
            secure: false,
            changeOrigin: true
          },
          {
            context: ['/payment', '/sso', '/auth', '/ledger'],
            target: 'https://mcdtest2019.huilianyi.com',
            secure: false,
            changeOrigin: true
          }, {
            context: ['/oauth'],
            target: 'https://mcdtest2019.huilianyi.com',
            secure: false,
            changeOrigin: true,
            pathRewrite: {'/oauth': '/auth/oauth'},
          }, {
            context: ['/ws/direction', '/ws/place'],
            target: 'http://apis.map.qq.com',
            secure: false,
            changeOrigin: true
          }, {
            context: ['/multilanguage'],
            target: 'https://cloudhelios-static.oss-cn-shanghai.aliyuncs.com',
            secure: false,
            changeOrigin: true
          }],
      },
      optimization: {
        splitChunks: {
          hidePathInfo: false,
          minSize: 10000,
          maxAsyncRequests: Infinity,
          maxInitialRequests: Infinity,
          cacheGroups: {
            vendor: { // 基本框架
              name: 'vendor',
              chunks: 'initial',
              test: /node_modules\//,
            }
          }
        },
      },
      plugins: [
        new HappyPack({
          id: 'happyBabel',
          loaders: [{
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            },
          }],
          threadPool: happyThreadPool,
          verbose: true,
        }),
        new HappyPack({
          id: 'happyScss',
          loaders: ['style-loader', 'css-loader', 'sass-loader', {
            loader: 'sass-resources-loader',
            options: {
              resources: path.resolve(__dirname, '../../src/styles/themes/color/default.scss'),
            }
          }],
          threadPool: happyThreadPool,
          verbose: true,
        }),
        new HappyPack({
          id: 'happyLess',
          loaders: ['style-loader', 'css-loader', {loader: 'less-loader', options: {javascriptEnabled: true}}],
          threadPool: happyThreadPool,
          verbose: true,
        }),
        new webpack.HotModuleReplacementPlugin(),
        new HtmlWebpackPlugin({
          filename: '../index.html',
          template: 'index.html',
          inject: true,
        }),
        new FriendlyErrors(),
        // 开发模式加速重启速度
        // new HardSourceWebpackPlugin({
        //   // Either an absolute path or relative to webpack's options.context.
        //   cacheDirectory: 'node_modules/.cache/hard-source/[confighash]',
        //   // Either a string of object hash function given a webpack config.
        //   configHash: function(webpackConfig) {
        //     // node-object-hash on npm can be used to build this.
        //     return require('node-object-hash')({sort: false}).hash(webpackConfig);
        //   },
        //   // Either false, a string, an object, or a project hashing function.
        //   environmentHash: {
        //     root: process.cwd(),
        //     directories: [],
        //     files: ['package-lock.json', 'yarn.lock'],
        //   },
        //   // An object.
        //   info: {
        //     // 'none' or 'test'.
        //     mode: 'none',
        //     // 'debug', 'log', 'info', 'warn', or 'error'.
        //     level: 'debug',
        //   },
        //   // Clean up large, old caches automatically.
        //   cachePrune: {
        //     // Caches younger than `maxAge` are not considered for deletion. They must
        //     // be at least this (default: 2 days) old in milliseconds.
        //     maxAge: 2 * 24 * 60 * 60 * 1000,
        //     // All caches together must be larger than `sizeThreshold` before any
        //     // caches will be deleted. Together they must be at least this
        //     // (default: 50 MB) big in bytes.
        //     sizeThreshold: 50 * 1024 * 1024
        //   },
        // }),
        // 是否开启分析
        // new BundleAnalyzerPlugin(),
      ]
    };
  }
}

module.exports = WebpackDevConfig;
